package moldat.utilities;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * Klasse zur Verarbeitung von Strings und URLS
 *
 * @author Sebastian Horwege
 *
 */
public class HTTPStringDownloader {

    private static HTTPStringDownloader downloader = null;

    public static HTTPStringDownloader getInstance() {
        if (downloader == null)
            downloader = new HTTPStringDownloader();
        return downloader;
    }

    /**
     * gibt neuen String zurück, mit Inhalt des Zielortes der URL
     *
     * @param url
     * @return
     * @throws IOException
     */
    public String HTTPtoString(URL url) throws IOException {
        int timeout = moldat.ApplicationConfig.getUrlTimeout();

        URLConnection urlConnection = url.openConnection();
        urlConnection.setConnectTimeout(timeout);
        urlConnection.setReadTimeout(timeout);
        BufferedReader breader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

        StringBuilder stringBuilder = new StringBuilder();

        String line;
        while ((line = breader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append("\n");
        }

        return stringBuilder.toString();
    }

    public void HTTPtoFile(URL url, File file) throws IOException {
        String content = HTTPtoString(url);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            byte[] buffer = content.getBytes();
            out.write(buffer);
            out.flush();
        } finally {
            out.close();
        }
    }
}
